package com.zx.tfw.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zx.tfw.dao.TechnicalFrameworkMapper;
import com.zx.tfw.entity.TechnicalFramework;
import com.zx.util.TfwInfoFromIneter;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class BatchService {

    @Autowired
    private TechnicalFrameworkMapper technicalFrameworkDao;

    public void getRemark() {
        final List<TechnicalFramework> all = this.technicalFrameworkDao
                .selectList(Wrappers.lambdaQuery());
        int threadNum = 10;
        LinkedBlockingQueue<TechnicalFramework> queue = new LinkedBlockingQueue<>(100);

        ExecutorService pool = Executors.newFixedThreadPool(threadNum);

        CountDownLatch latch = new CountDownLatch(threadNum);

        pool.submit(() -> {
            for (TechnicalFramework tfw : all) {
                try {
                    queue.put(tfw);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            latch.countDown();

        });

        for (int i = 0; i < threadNum - 1; i++) {
            pool.submit(() -> {
                try {
                    TechnicalFramework tfw = null;
                    while ((tfw = queue.poll(5, TimeUnit.SECONDS)) != null) {
                        String remark = TfwInfoFromIneter.getRemark(tfw.getNameAcronym());
                        if (!StringUtils.isEmpty(remark)) {
                            tfw.setRemark(remark.substring(0, Math.min(1000 * 5, remark.length())));
                            this.technicalFrameworkDao.insert(tfw);
                            System.out.println(tfw.getId() + "~~~~~~~~~~" + remark.length());
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                latch.countDown();
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }


}
